knitr::opts_chunk$set(fig.width=5, fig.height=5) 

rm(list=ls())



options(scipen=999)

library(tidyverse)
library(broom)
library(lubridate)
library(stargazer)
library(interflex)
library(reshape2)
pkgs <- c("dplyr", "ggplot2", "stargazer", "car", "tidyverse", "extrafont", "haven", "coefplot", "plotrix", "sensemakr", "cjoint")
# A function to load all above packages. Install if they have not been installed.
usePackage <- function(p){
  for (pkg in p){
    if (!is.element(pkg, installed.packages()[,1]))
      install.packages(pkg, dep = TRUE, repos = "https://cloud.r-project.org/")
    require(pkg, character.only = TRUE)
  }
}
usePackage(pkgs)


d0 <- read.csv("Study 4 Data.csv")
#d0 <- read.csv("2024_02_Bram_CivicPulse_RESTRICTED.csv")







d0$Conjoint1_SC <- ifelse(d0$Conjoint1_SC == "Scenario A", 1, 0)
d0$Conjoint2_SC <- ifelse(d0$Conjoint2_SC == "Scenario A", 1, 0)
d0$Conjoint3_SC <- ifelse(d0$Conjoint3_SC == "Scenario A", 1, 0)



d0$Republican <- 0
d0$Republican[d0$Demo_party_SC == "Republican " | d0$Demo_partylean_SC == "Republican Party"] <- 1
d0$Democrat <- 0
d0$Democrat[d0$Demo_party_SC == "Democrat " | d0$Demo_partylean_SC == "Democratic Party "] <- 1

d0$Independent <- as.numeric(ifelse(d0$Democrat == 1 | d0$Republican == 1, 0, 1))

#d0$Education <- as.numeric(d0$Demo_education_SC)

d0$CollegeDegree <- ifelse(d0$Demo_education_SC == "College graduate" | d0$Demo_education_SC == "Graduate degree", "Yes", "No")

d0$PriorGovtJob <- ifelse(d0$Demo_jobprior_MS_gov == 1, "Yes", "No")
  
d0$StrongIdeologue <- ifelse(d0$Demo_ideo_SC == "Very conservative " | d0$Demo_ideo_SC == "Very liberal ", "Yes", "No")

#restricted data
#d0$CompetitiveElection <- as.factor(ifelse(d0$Gov_Trumpshare_restricted > .45 & d0$Gov_Trumpshare_restricted < .55, "Yes", "No"))

d0$UncontenstedElection <- as.factor(ifelse(d0$Demo_winmarg_SC == "I did not face a contested election", "Yes", "No"))

d0$BigMargin <- as.factor(ifelse(d0$Demo_winmarg_SC == "More than 30%", "Yes", "No"))



d1 <- subset(d0, d0$Independent !=1)

d1$InParty <- d1$Inparty2_QD



### DESCRIPTIVES




summary(as.factor(d0$Civillib_min_SC))
summary(as.factor(d0$Civillib_const_SC))
summary(as.factor(d0$Civillib_speech_SC))


d0$Party <- ifelse(d0$Democrat == 1, "Democrat",
                   ifelse(d0$Republican == 1, "Republican", NA))

civillib_min_SC_summary <- table(d0$Party, d0$Civillib_min_SC) / rowSums(table(d0$Party, d0$Civillib_min_SC)) * 100

# Calculate percentages for Civil Liberties in the context of Constitutionality at the Supreme Court level
civillib_const_SC_summary <- table(d0$Party, d0$Civillib_const_SC) / rowSums(table(d0$Party, d0$Civillib_const_SC)) * 100

# Calculate percentages for Civil Liberties concerning Speech at the Supreme Court level
civillib_speech_SC_summary <- table(d0$Party, d0$Civillib_speech_SC) / rowSums(table(d0$Party, d0$Civillib_speech_SC)) * 100


# New data based on the provided summaries
data <- data.frame(
  Measure = rep(c("Majority Ignores Minority", "Majority Violates Constitution", "Majority Bans Speech"), each = 6),
  Party = rep(c("Democrat", "Republican"), times = 9),
  Category = rep(c(0, 0.5, 1), times = 6),
  Value = c(
    # Majority Ignores Minority
    1.169591, 7.602339, 91.228070, # Democrat: Yes, Neither, No
    3.703704, 10.648148, 85.648148, # Republican: Yes, Neither, No
    
    # Majority Violates Constitution
    10.588235, 21.176471, 68.235294, # Democrat: Yes, Neither, No
    4.109589, 7.762557, 88.127854, # Republican: Yes, Neither, No
    
    # Majority Bans Speech
    2.339181, 15.204678, 82.456140, # Democrat: Yes, Neither, No
    6.481481, 14.814815, 78.703704 # Republican: Yes, Neither, No
  )
)


# Transforming the data into a tidy format
data <- data %>%
  mutate(Category = factor(Category, levels = c(1, 0.5, 0), labels = c("No", "Neither", "Yes")),
         Measure = factor(Measure, levels = c("Majority Ignores Minority", "Majority Violates Constitution", "Majority Bans Speech")))

# Plotting with updated adjustments
todaypolicymakers<-ggplot(data, aes(x = Category, y = Value, fill = Party)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  facet_wrap(~Measure, scales = "free") +
  scale_fill_manual(values = c("Democrat" = "blue", "Republican" = "red")) +
  scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 10)) +
  labs(title = "Local Policymaker Comparison of Political Party Positions",
       x = "Category",
       y = "Percentage",
       fill = "Party") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        legend.position = "bottom",
        plot.title = element_text(hjust = 0.5)) # Correctly centering the title
ggsave("todaypolicymakers.jpeg", width = 6, height = 6, units = "in", dpi = 500)





## Conjoint:

### NATIONAL ELECT

# Trial 1, Scenario A
d1$Nat_elect_QD_1A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Nat_elect_QD_1A)
d1$Nat_elect_QD_1A <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Nat_elect_QD_1A)

# Trial 1, Scenario B
d1$Nat_elect_QD_1B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Nat_elect_QD_1B)
d1$Nat_elect_QD_1B <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Nat_elect_QD_1B)

# Trial 2, Scenario A
d1$Nat_elect_QD_2A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Nat_elect_QD_2A)
d1$Nat_elect_QD_2A <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Nat_elect_QD_2A)

# Trial 2, Scenario B
d1$Nat_elect_QD_2B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Nat_elect_QD_2B)
d1$Nat_elect_QD_2B <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Nat_elect_QD_2B)

# Trial 3, Scenario A
d1$Nat_elect_QD_3A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Nat_elect_QD_3A)
d1$Nat_elect_QD_3A <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Nat_elect_QD_3A)

# Trial 3, Scenario B
d1$Nat_elect_QD_3B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Nat_elect_QD_3B)
d1$Nat_elect_QD_3B <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Nat_elect_QD_3B)

### LOCAL ELECT

# Trial 1, Scenario A
d1$Local_elect_QD_1A <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Local_elect_QD_1A)
d1$Local_elect_QD_1A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Local_elect_QD_1A)

# Trial 1, Scenario B
d1$Local_elect_QD_1B <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Local_elect_QD_1B)
d1$Local_elect_QD_1B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Local_elect_QD_1B)

# Trial 2, Scenario A
d1$Local_elect_QD_2A <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Local_elect_QD_2A)
d1$Local_elect_QD_2A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Local_elect_QD_2A)

# Trial 2, Scenario B
d1$Local_elect_QD_2B <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Local_elect_QD_2B)
d1$Local_elect_QD_2B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Local_elect_QD_2B)

# Trial 3, Scenario A
d1$Local_elect_QD_3A <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Local_elect_QD_3A)
d1$Local_elect_QD_3A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Local_elect_QD_3A)

# Trial 3, Scenario B
d1$Local_elect_QD_3B <- gsub("\\$\\{e://Field/Inparty_QD\\}", "In-party", d1$Local_elect_QD_3B)
d1$Local_elect_QD_3B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Local_elect_QD_3B)


### LEGISLATIVE CHANGE

# Trial 1, Scenario A
d1$Leg_change_QD_1A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Leg_change_QD_1A)
d1$Leg_change_QD_1A <- gsub("\\$\\{e://Field/Outparty2_QD\\}", "Out-party", d1$Leg_change_QD_1A)

# Trial 1, Scenario B
d1$Leg_change_QD_1B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Leg_change_QD_1B)
d1$Leg_change_QD_1B <- gsub("\\$\\{e://Field/Outparty2_QD\\}", "Out-party", d1$Leg_change_QD_1B)

# Trial 2, Scenario A
d1$Leg_change_QD_2A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Leg_change_QD_2A)
d1$Leg_change_QD_2A <- gsub("\\$\\{e://Field/Outparty2_QD\\}", "Out-party", d1$Leg_change_QD_2A)

# Trial 2, Scenario B
d1$Leg_change_QD_2B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Leg_change_QD_2B)
d1$Leg_change_QD_2B <- gsub("\\$\\{e://Field/Outparty2_QD\\}", "Out-party", d1$Leg_change_QD_2B)

# Trial 3, Scenario A
d1$Leg_change_QD_3A <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Leg_change_QD_3A)
d1$Leg_change_QD_3A <- gsub("\\$\\{e://Field/Outparty2_QD\\}", "Out-party", d1$Leg_change_QD_3A)

# Trial 3, Scenario B
d1$Leg_change_QD_3B <- gsub("\\$\\{e://Field/Outparty_QD\\}", "Out-party", d1$Leg_change_QD_3B)
d1$Leg_change_QD_3B <- gsub("\\$\\{e://Field/Outparty2_QD\\}", "Out-party", d1$Leg_change_QD_3B)


d<-mutate(d1, ID = row_number())


################
list1 <- list(
  NatElect = list(
    ~ Nat_elect_QD_1A + Nat_elect_QD_2A + Nat_elect_QD_3A ,
    ~ Nat_elect_QD_1B + Nat_elect_QD_2B + Nat_elect_QD_3B ),
  LocalElect = list(
    ~ Local_elect_QD_1A + Local_elect_QD_2A + Local_elect_QD_3A ,
    ~ Local_elect_QD_1B + Local_elect_QD_2B + Local_elect_QD_3B),
  LegChange = list(
    ~ Leg_change_QD_1A+ Leg_change_QD_2A +Leg_change_QD_3A ,
    ~ Leg_change_QD_1B+ Leg_change_QD_2B+Leg_change_QD_3B),
  SalChange = list(
    ~ Sal_change_QD_1A+Sal_change_QD_2A+Sal_change_QD_3A,
    ~ Sal_change_QD_1B+Sal_change_QD_2B+Sal_change_QD_3B)
)
# task variables
list2 <- list(choice = ~ Conjoint1_SC + Conjoint2_SC + Conjoint3_SC )

library(cregg)
# perform reshape
str(long <- cj_tidy(d,
                    profile_variables = list1,
                    task_variables = list2,
                    id = ~ ID))
stopifnot(nrow(long) == nrow(d)*3*2)

# recode outcome so it is coded sensibly
long$chosen <- ifelse((long$profile == "A" & long$choice == 1) | 
                        (long$profile == "B" & long$choice == 0), 1, 0)

long <- subset(long, long$chosen != "NA")

long$NatElect <- gsub("Out-party win", "Out-party wins", long$NatElect)
long$NatElect <- gsub("In-party win", "In-party wins", long$NatElect)
long$NatElect <- gsub("take control of Congress", "takes control of Congress", long$NatElect)
long$LocalElect <- gsub("take control of", "takes control of", long$LocalElect)
long$LegChange <- gsub("a Out-party candidate", "an out-party candidate", long$LegChange)
long$LegChange <- gsub("all Out-party", "all out-party members", long$LegChange)
long$LegChange <- gsub("some Out-party", "some out-party members", long$LegChange)
long$LegChange <- gsub("restricts a Out-party candidate", "restricts an out-party candidate", long$LegChange)



long$Presidential_Election_Outcome_2024 <- factor(long$NatElect, levels = c("Out-party wins the Presidency and takes control of Congress.",
                                                                            "Out-party wins the Presidency but Congress is divided.",
                                                                            "In-party wins the Presidency but Congress is divided.",
                                                                            "In-party wins the Presidency and takes control of Congress."))

long$Local_Election_Outcome_2024 <- factor(long$LocalElect, levels = c("Out-party takes control of your local governing board.",
                                                                       "Your local governing board is evenly split between Democrats and Republicans.",
                                                                       "In-party takes control of your local governing board."))

long$Antidemocratic_Legislation <- factor(long$LegChange, levels = c("The state legislature recommends a cap on the number of campaign volunteers, applying to all candidates in state and local campaigns.",
                                                                     "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies.",
                                                                     "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies.",
                                                                     "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies.",
                                                                     "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies."))

long$Salary_Change <- factor(long$SalChange, levels = c("The state legislature leaves your pay unchanged.",
                                                        "The state legislature cuts your pay by 20%.",
                                                        "The state legislature cuts your pay by 10%.",
                                                        "The state legislature cuts your pay by 5%.",
                                                        "The state legislature raises your pay by 5%.",
                                                        "The state legislature raises your pay by 10%.",
                                                        "The state legislature raises your pay by 20%."))

long$ID <- as.factor(long$ID)
#####order factors######
long <- within(long, Presidential_Election_Outcome_2024 <- relevel(Presidential_Election_Outcome_2024, ref = "Out-party wins the Presidency and takes control of Congress."))
long <- within(long, Local_Election_Outcome_2024 <- relevel(Local_Election_Outcome_2024, ref = "Your local governing board is evenly split between Democrats and Republicans."))
long <- within(long, Antidemocratic_Legislation <- relevel(Antidemocratic_Legislation, ref = "The state legislature recommends a cap on the number of campaign volunteers, applying to all candidates in state and local campaigns."))
long <- within(long, Salary_Change <- relevel(Salary_Change, ref = "The state legislature leaves your pay unchanged."))

f1<-cj(long, chosen ~ Presidential_Election_Outcome_2024 + Local_Election_Outcome_2024 + Antidemocratic_Legislation  + Salary_Change, id = ~ ID)
plot(f1, xlab = "Estimated AMCE (Change in Probability of Profile Selected)", level_order = c("descending"))
library(cjoint)
detach("package:cregg", unload = TRUE)

long <- long[!is.na(long$Antidemocratic_Legislation), ]

# Then run your model on this subset of data
f1Main<-amce(chosen ~Presidential_Election_Outcome_2024 + Local_Election_Outcome_2024 + Antidemocratic_Legislation  + Salary_Change, data= long, cluster=TRUE, respondent.id= "ID")





library(cregg)




mm1 <- mm(long, chosen ~ Antidemocratic_Legislation+ Local_Election_Outcome_2024 +  Presidential_Election_Outcome_2024  + Salary_Change, id = ~ ID)




######## PLOT FOR AMCE
# Create vectors for the attributes, levels, estimates, and standard errors
attributes <- c(
  "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation",
  "Local Election Outcome 2024", "Local Election Outcome 2024",
  "Presidential Election Outcome 2024", "Presidential Election Outcome 2024", "Presidential Election Outcome 2024",
  "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change"
)

levels <- c(
  "Restricts out-party candidate advertising", "Bans out-party candidate", "Bans some out-party members", "Bans all out-party members",
  "Out-party takes local board", "In-party takes local board",
  "Out-party wins Presidency, divided Congress", "In-party wins Presidency, divided Congress", "In-party wins Presidency & Congress",
  "Legislature cuts pay by 20%", "Legislature cuts pay by 10%", "Legislature cuts pay by 5%",
  "Legislature raises pay by 5%", "Legislature raises pay by 10%", "Legislature raises pay by 20%"
)

summary(f1Main)
estimates <- c(-0.0437954, -0.0787197, -0.1217270, -0.2022350, 
               -0.1558702, -0.0186192, 0.2244558, 0.4765559, 0.5673831,
               -0.0627786, -0.0195846, -0.0070590, 0.0188375, -0.0051269, -0.0468885)

std_errs <- c(0.031198, 0.031386, 0.031219, 0.032309, 
              0.025144, 0.024566, 0.025612, 0.028414, 0.027355, 
              0.034115, 0.034443, 0.034459, 0.032631, 0.035166, 0.031558)



# Calculate the 95% confidence intervals
lower_bounds <- estimates - (1.96 * std_errs)
upper_bounds <- estimates + (1.96 * std_errs)

# Combine into a data frame
results_df <- data.frame(
  Attribute = attributes,
  Level = levels,
  Estimate = estimates,
  StdErr = std_errs,
  LowerCI = lower_bounds,
  UpperCI = upper_bounds
)

# View the data frame
print(results_df)

library(ggplot2)
library(dplyr)

# Assuming results_df is your original data frame
# Add the 'Significant' column based on the 95% confidence interval
results_df$Significant <- with(results_df, LowerCI > 0 | UpperCI < 0)

# Update baseline levels with the correct labels
baseline_levels <- data.frame(
  Attribute = c("Antidemocratic Legislation", "Local Election Outcome 2024", 
                "Presidential Election Outcome 2024", "Salary Change"),
  Level = c("Non-binding cap on campaign volunteers", "Local board evenly divided", 
            "Out-party wins Presidency & Congress", "Legislature leaves pay unchanged"),
  Estimate = 0,
  StdErr = 0,
  LowerCI = 0,
  UpperCI = 0,
  Significant = TRUE
)

# Combine baseline levels with results_df
results_with_baseline <- rbind(results_df, baseline_levels)


# Create the plot
ggplot(results_with_baseline, aes(x = reorder(Level, Estimate), y = Estimate, fill = Significant)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("grey", NA)) +
  coord_flip() +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), width = 0.4, color = "black") +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "AMCE Estimate", title = "") +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white", colour = "white"), 
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line = element_line(colour = "black") 
  )

 #Save the plot
ggsave("cpamce.jpeg", width = 6, height = 6, units = "in", dpi = 500)

### MARGINAL MEANS

mm_results <- mm(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                   Presidential_Election_Outcome_2024 + Salary_Change, id = ~ ID)

# Assuming mm_results is already your marginal means data frame
mm_data_frame <- mm_results

# Filter to keep only relevant columns
mm_data_frame <- mm_data_frame[, c("feature", "level", "estimate", "std.error", "lower", "upper")]

# Rename the columns for clarity
colnames(mm_data_frame) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI")
mm_data_frame$Attribute <- gsub("_", " ", mm_data_frame$Attribute) # Replace underscores with spaces

# Named vector for new labels with correct current levels
new_labels <- c(
  "The state legislature recommends a cap on the number of campaign volunteers, applying to all candidates in state and local campaigns." = "Non-binding cap on campaign volunteers",
  "The state legislature restricts an out-party candidate from advertising in state and local campaigns in response to recent controversies." = "Restricts out-party candidate advertising",
  "The state legislature bans an out-party candidate from competing in state and local campaigns in response to recent controversies." = "Bans out-party candidate",
  "The state legislature bans some out-party members from competing in state and local campaigns in response to recent controversies." = "Bans some out-party members",
  "The state legislature bans all out-party members from competing in state and local campaigns in response to recent controversies." = "Bans all out-party members",
  "Your local governing board is evenly split between Democrats and Republicans." = "Local board evenly divided",
  "Out-party takes control of your local governing board." = "Out-party takes local board",
  "In-party takes control of your local governing board." = "In-party takes local board",
  "Out-party wins the Presidency and takes control of Congress." = "Out-party wins Presidency & Congress",
  "Out-party wins the Presidency but Congress is divided." = "Out-party wins Presidency, divided Congress",
  "In-party wins the Presidency but Congress is divided." = "In-party wins Presidency, divided Congress",
  "In-party wins the Presidency and takes control of Congress." = "In-party wins Presidency & Congress",
  "The state legislature leaves your pay unchanged." = "Legislature leaves pay unchanged",
  "The state legislature cuts your pay by 20%." = "Legislature cuts pay by 20%",
  "The state legislature cuts your pay by 10%." = "Legislature cuts pay by 10%",
  "The state legislature cuts your pay by 5%." = "Legislature cuts pay by 5%",
  "The state legislature raises your pay by 5%." = "Legislature raises pay by 5%",
  "The state legislature raises your pay by 10%." = "Legislature raises pay by 10%",
  "The state legislature raises your pay by 20%." = "Legislature raises pay by 20%"
)

# Create the plot with enhanced aesthetics and new level labels
ggplot(mm_data_frame, aes(x = reorder(Level, Estimate), y = Estimate)) +
  geom_point(aes(color = Estimate), size = 3) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), width = 0.4, color = "black") +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "none"
  ) +
  scale_color_gradient(low = "black", high = "black") +
  scale_x_discrete(labels = new_labels) # Apply new labels

ggsave("cpmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)

## Marginal means partisans:

long$InParty <- as.factor(long$InParty)

mm_resultsPID <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                      Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ InParty)

mm_resultsPID_df <- as.data.frame(mm_resultsPID)

# Ensure the dataframe has the necessary columns
mm_resultsPID_df <- mm_resultsPID_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "InParty")]

# Rename the columns for clarity
colnames(mm_resultsPID_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "InParty")
mm_resultsPID_df$Attribute <- gsub("_", " ", mm_resultsPID_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsPID_df$Level <- factor(mm_resultsPID_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsPID_df, aes(x = reorder(Level, Estimate), y = Estimate, color = InParty)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Democrat" = "blue", "Republican" = "red")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("partisanmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)


## Marginal means Education:

long$CollegeEducation <- as.factor(long$CollegeDegree)

mm_resultsCollege <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                          Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ CollegeEducation)

mm_resultsCollege_df <- as.data.frame(mm_resultsCollege)

# Ensure the dataframe has the necessary columns
mm_resultsCollege_df <- mm_resultsCollege_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "CollegeEducation")]

# Rename the columns for clarity
colnames(mm_resultsCollege_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "CollegeEducation")
mm_resultsCollege_df$Attribute <- gsub("_", " ", mm_resultsCollege_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsCollege_df$Level <- factor(mm_resultsCollege_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsCollege_df, aes(x = reorder(Level, Estimate), y = Estimate, color = CollegeEducation)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("educationmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)


## Marginal means StrongIdeologue:


long$StrongIdeologue <- as.factor(long$StrongIdeologue)

mm_resultsIdeologue <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                            Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ StrongIdeologue)

mm_resultsIdeologue_df <- as.data.frame(mm_resultsIdeologue)

# Ensure the dataframe has the necessary columns
mm_resultsIdeologue_df <- mm_resultsIdeologue_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "StrongIdeologue")]

# Rename the columns for clarity
colnames(mm_resultsIdeologue_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "StrongIdeologue")
mm_resultsIdeologue_df$Attribute <- gsub("_", " ", mm_resultsIdeologue_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsIdeologue_df$Level <- factor(mm_resultsIdeologue_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsIdeologue_df, aes(x = reorder(Level, Estimate), y = Estimate, color = StrongIdeologue)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("ideologuemm.jpeg", width = 6, height = 6, units = "in", dpi = 500)


## PRIOR GOVT JOB



long$PriorGovtJob <- as.factor(long$PriorGovtJob)

mm_resultsPriorGov <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                            Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ PriorGovtJob)

mm_resultsPriorGov_df <- as.data.frame(mm_resultsPriorGov)

# Ensure the dataframe has the necessary columns
mm_resultsPriorGov_df <- mm_resultsPriorGov_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "PriorGovtJob")]

# Rename the columns for clarity
colnames(mm_resultsPriorGov_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "PriorGovtJob")
mm_resultsPriorGov_df$Attribute <- gsub("_", " ", mm_resultsPriorGov_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsPriorGov_df$Level <- factor(mm_resultsPriorGov_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsPriorGov_df, aes(x = reorder(Level, Estimate), y = Estimate, color = PriorGovtJob)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("priorgovmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)

### COMP. ELECTION:


mm_resultsCompElect <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                           Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ CompetitiveElection)

mm_resultsCompElect_df <- as.data.frame(mm_resultsCompElect)

# Ensure the dataframe has the necessary columns
mm_resultsCompElect_df <- mm_resultsCompElect_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "CompetitiveElection")]

# Rename the columns for clarity
colnames(mm_resultsCompElect_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "CompetitiveElection")
mm_resultsCompElect_df$Attribute <- gsub("_", " ", mm_resultsCompElect_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsCompElect_df$Level <- factor(mm_resultsCompElect_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsCompElect_df, aes(x = reorder(Level, Estimate), y = Estimate, color = CompetitiveElection)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("compelectmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)



### BigMargin


mm_resultsBigMargin <- cj(long, chosen ~ Antidemocratic_Legislation + Local_Election_Outcome_2024 + 
                            Presidential_Election_Outcome_2024 + Salary_Change, estimate = "mm", id = ~ ID, by = ~ BigMargin)

mm_resultsBigMargin_df <- as.data.frame(mm_resultsBigMargin)

# Ensure the dataframe has the necessary columns
mm_resultsBigMargin_df <- mm_resultsBigMargin_df[, c("feature", "level", "estimate", "std.error", "lower", "upper", "BigMargin")]

# Rename the columns for clarity
colnames(mm_resultsBigMargin_df) <- c("Attribute", "Level", "Estimate", "StdError", "LowerCI", "UpperCI", "BigMargin")
mm_resultsBigMargin_df$Attribute <- gsub("_", " ", mm_resultsBigMargin_df$Attribute) # Replace underscores with spaces

# Apply new labels
mm_resultsBigMargin_df$Level <- factor(mm_resultsBigMargin_df$Level, levels = names(new_labels), labels = new_labels)

ggplot(mm_resultsBigMargin_df, aes(x = reorder(Level, Estimate), y = Estimate, color = BigMargin)) +
  geom_point(position = position_dodge(width = 0.75), size = 1.5) +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), 
                position = position_dodge(width = 0.75), 
                width = 0.1,
                linewidth = 0.5) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "black") +
  coord_flip() +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "Marginal Mean", title = "") +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),    # Remove major grid lines
    panel.grid.minor = element_blank(),    # Remove minor grid lines
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line.y = element_line(color = "black"),
    axis.ticks.y = element_line(color = "black"),
    axis.line = element_line(colour = "black"),
    legend.position = "bottom"             # Move legend to bottom
  ) +
  scale_color_manual(values = c("Yes" = "black", "No" = "grey")) +
  scale_x_discrete(labels = new_labels)  # Define your 'new_labels' vector as done previously

ggsave("bigmarginmm.jpeg", width = 6, height = 6, units = "in", dpi = 500)



### COMBINED GRAPH WITH GP

######### Experiment 1 Data

# Create vectors for the attributes, levels, estimates, and standard errors
attributes1 <- c(
  "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation",
  "Local Election Outcome 2024", "Local Election Outcome 2024",
  "Presidential Election Outcome 2024", "Presidential Election Outcome 2024", "Presidential Election Outcome 2024",
  "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change"
)

levels1 <- c(
  "Restricts out-party candidate advertising", "Bans out-party candidate", "Bans some out-party members", "Bans all out-party members",
  "Out-party takes local board", "In-party takes local board",
  "Out-party wins Presidency, divided Congress", "In-party wins Presidency, divided Congress", "In-party wins Presidency & Congress",
  "Salary changes by -20%", "Salary changes by -10%", "Salary changes by -5%",
  "Salary changes by +5%", "Salary changes by +10%", "Salary changes by +20%"
)

estimates1 <- c(-0.0437954, -0.0787197, -0.1217270, -0.2022350, 
                -0.1558702, -0.0186192, 0.2244558, 0.4765559, 0.5673831,
                -0.0627786, -0.0195846, -0.0070590, 0.0188375, -0.0051269, -0.0468885)

std_errs1 <- c(0.031198, 0.031386, 0.031219, 0.032309, 
               0.025144, 0.024566, 0.025612, 0.028414, 0.027355, 
               0.034115, 0.034443, 0.034459, 0.032631, 0.035166, 0.031558)

# Calculate the 95% confidence intervals
lower_bounds1 <- estimates1 - (1.96 * std_errs1)
upper_bounds1 <- estimates1 + (1.96 * std_errs1)

# Combine into a data frame
results_df1 <- data.frame(
  Attribute = attributes1,
  Level = levels1,
  Estimate = estimates1,
  StdErr = std_errs1,
  LowerCI = lower_bounds1,
  UpperCI = upper_bounds1,
  Experiment = "Local Elected Leaders"
)

######### Experiment 2 Data

attributes2 <- c(
  "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation", "Antidemocratic Legislation",
  "Local Election Outcome 2024", "Local Election Outcome 2024",
  "Presidential Election Outcome 2024", "Presidential Election Outcome 2024", "Presidential Election Outcome 2024",
  "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change", "Salary Change"
)

levels2 <- c(
  "Restricts out-party candidate advertising", "Bans out-party candidate", "Bans some out-party members", "Bans all out-party members",
  "Out-party takes local board", "In-party takes local board",
  "Out-party wins Presidency, divided Congress", "In-party wins Presidency, divided Congress", "In-party wins Presidency & Congress",
  "Salary changes by -20%", "Salary changes by -10%", "Salary changes by -5%",
  "Salary changes by +5%", "Salary changes by +10%", "Salary changes by +20%"
)

estimates2 <- c(-0.017408, -0.015756, -0.020168, -0.081401,
                -0.092204, 0.021732,
                0.099605, 0.275375, 0.342706,
                -0.250312, -0.158960, -0.053166,
                0.080555, 0.113682, 0.179243)

std_errs2 <- c(0.019007, 0.018977, 0.018737, 0.020005,
               0.014427, 0.014749,
               0.018093, 0.017895, 0.018260,
               0.023356, 0.023789, 0.024399,
               0.024000, 0.023451, 0.023516)

# Calculate the 95% confidence intervals
lower_bounds2 <- estimates2 - (1.96 * std_errs2)
upper_bounds2 <- estimates2 + (1.96 * std_errs2)

# Combine into a data frame
results_df2 <- data.frame(
  Attribute = attributes2,
  Level = levels2,
  Estimate = estimates2,
  StdErr = std_errs2,
  LowerCI = lower_bounds2,
  UpperCI = upper_bounds2,
  Experiment = "General Population"
)

######## Combine Both Experiments

results_combined <- rbind(results_df1, results_df2)

# Add baseline levels for both experiments
baseline_levels_exp1 <- data.frame(
  Attribute = c("Antidemocratic Legislation", "Local Election Outcome 2024", 
                "Presidential Election Outcome 2024", "Salary Change"),
  Level = c("Non-binding cap on campaign volunteers", "Local board evenly divided", 
            "Out-party wins Presidency & Congress", "Salary changes by 0%"),
  Estimate = 0,
  StdErr = 0,
  LowerCI = 0,
  UpperCI = 0,
  Experiment = "Local Elected Leaders"
)

baseline_levels_exp2 <- data.frame(
  Attribute = c("Antidemocratic Legislation", "Local Election Outcome 2024", 
                "Presidential Election Outcome 2024", "Salary Change"),
  Level = c("Non-binding cap on campaign volunteers", "Local board evenly divided", 
            "Out-party wins Presidency & Congress", "Salary changes by 0%"),
  Estimate = 0,
  StdErr = 0,
  LowerCI = 0,
  UpperCI = 0,
  Experiment = "General Population"
)

baseline_levels_combined <- rbind(baseline_levels_exp1, baseline_levels_exp2)

# Combine baseline levels with the full results
results_combined_with_baseline <- rbind(results_combined, baseline_levels_combined)

######## Plot

library(ggplot2)

ggplot(results_combined_with_baseline, aes(x = reorder(Level, Estimate), y = Estimate, fill = Experiment)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +
  coord_flip() +
  geom_errorbar(aes(ymin = LowerCI, ymax = UpperCI), width = 0.4, color = "black", position = position_dodge(width = 0.8)) +
  facet_wrap(~Attribute, scales = "free_y", ncol = 1) +
  labs(x = "", y = "AMCE Estimate") +
  scale_fill_manual(values = c("Local Elected Leaders" = "#76B7B2", "General Population" = "gray")) +
  theme_minimal() +
  theme(
    legend.position = "bottom",
    legend.title = element_blank(),
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white", colour = "white"), 
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line = element_line(colour = "black") 
  )

ggsave("combined_cpamce.jpeg", width = 10, height = 8, units = "in", dpi = 500)


